import {
  Component,
  OnInit,
  ViewChild,
  HostBinding,
  Inject,
  OnDestroy
} from "@angular/core";
import { MatPaginator, MatSort, MatTableDataSource } from "@angular/material";
import { LocaleService, TranslationService, Language } from "angular-l10n";
import { AssetsItem, ISelectAssetsRequest } from "@/assets/store/models/assets";

import { Store, select } from "@ngrx/store";
import * as fromUser from "@/user/store/reducers/index";
import * as fromTrade from "@/trade/store/reducers/index";
import * as fromAssets from "@/assets/store/reducers/index";
import * as fromRoot from "@/reducers/index";
import { map, filter, skip } from "rxjs/operators";
import { Subscription } from "rxjs";
import { AssetsActions } from "@/assets/store/actions";
import { FormControl } from "@angular/forms";
import { forkJoin, combineLatest, zip } from "rxjs";
import { combineAll, debounceTime } from "rxjs/operators";
import { Router, NavigationEnd } from "@angular/router";
import { ActivatedRoute } from "@angular/router";
import createNumberMask from "text-mask-addons/dist/createNumberMask.js";

/**
 * @title Table with pagination
 */
@Component({
  selector: "app-assets-lists",
  templateUrl: "./assets-lists.component.html",
  styleUrls: ["./assets-lists.component.scss"]
})
export class AssetsListsComponent implements OnInit, OnDestroy {
  public search: FormControl = new FormControl("");
  public hideSmall: FormControl = new FormControl(false);

  public mask = {
    mask: createNumberMask({
      prefix: "",
      suffix: ""
    })
  };

  @Language() lang: string;

  displayedColumns: string[] = ["coin", "amount", "ava", "frozen", "action"];

  assetsLists: Array<AssetsItem> = [];

  dataSource;

  @HostBinding("style.width")
  public width = "100%";

  @ViewChild(MatSort) sort: MatSort;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  req: ISelectAssetsRequest = {
    uid: "",
    search: "",
    hideSmall: false
  };

  sub$ = {
    hideSmallSub$: null,
    userSub$: null,
    assetsListsSub$: null,
    searchSub$: null,
    assetsToBtcSub$: null
  };

  assetsLists$ = this.store
    .pipe(select(fromRoot.assetsLists))
    .pipe(filter(assetsLists => !!assetsLists));

  assetsToBtc$ = this.store
    .pipe(select(fromRoot.assetsToBtc))
    .pipe(filter(assetsToBtc => !!assetsToBtc));

  // type any need to optimize
  assetsListsSub$: any;

  user$ = this.store.pipe(
    select(fromRoot.user),
    filter(user => !!user)
  );

  assetsToBtc = {
    ava: "",
    frozen: "",
    total: ""
  };

  constructor(
    @Inject("AssetsService") private assetsService,
    @Inject("UtilsService") private utilsService,
    private store: Store<
      fromTrade.State | fromUser.State | fromAssets.State | fromRoot.State
    >,
    private router: Router,
    private activeRouter: ActivatedRoute
  ) {}

  ngOnInit() {
    this.store.dispatch(new AssetsActions.FindAssetsToBtc({ req: {} }));
    this.req.search = this.search.value;
    this.req.hideSmall = this.hideSmall.value;
    this.addListen();
  }

  addListen() {
    this.sub$.userSub$ = this.user$.subscribe(e => {
      // this.req.uid = e.id;
      this.store.dispatch(new AssetsActions.SelectAssets({ req: this.req }));
    });

    this.sub$.assetsListsSub$ = this.assetsLists$.subscribe(assetsLists => {
      this.dataSource = new MatTableDataSource(assetsLists);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    });

    this.sub$.assetsToBtcSub$ = this.assetsToBtc$.subscribe(e => {
      this.assetsToBtc = e;
    });

    this.sub$.searchSub$ = this.search.valueChanges
      .pipe(debounceTime(500))
      .subscribe(e => {
        this.req.search = e;
        this.req.hideSmall = this.hideSmall.value;
        this.store.dispatch(
          new AssetsActions.SelectAssets({
            req: {
              ...this.req
            }
          })
        );
      });

    this.sub$.hideSmallSub$ = this.hideSmall.valueChanges
      .pipe(debounceTime(500))
      .subscribe(e => {
        this.req.search = this.search.value;
        this.req.hideSmall = e;
        this.store.dispatch(
          new AssetsActions.SelectAssets({
            req: {
              ...this.req
            }
          })
        );
      });
  }

  toDeposit(e) {
    this.router.navigate(["/assets/deposit"], {
      queryParams: { coin: e.coin }
    });
  }

  toWithdraw(e) {
    this.router.navigate(["/assets/withdraw"], {
      queryParams: { coin: e.coin }
    });
  }

  toExchange() {}

  onInputSearch(e) {
    this.search.setValue(e.target.value);
  }

  ngOnDestroy() {
    this.utilsService.unsub(this.sub$);
  }
}
